package com.abcode.nettyserverwebsocket.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;
 public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
     private static ConcurrentHashMap<String, ChannelHandlerContext> channelMap = new ConcurrentHashMap<>();
     @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 新连接建立时保存连接状态
        channelMap.put(ctx.channel().id().asLongText(), ctx);
         ctx.channel().writeAndFlush(new TextWebSocketFrame("连接成功了"));
         System.out.println("有人来了：" + ctx.channel().id() + "--"+ LocalDateTime.now());
        super.channelActive(ctx);

    }
     @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 连接断开时移除连接状态
        channelMap.remove(ctx.channel().id().asLongText());
         System.out.println("有人走了：" + ctx.channel().id() + "--"+ LocalDateTime.now());
        super.channelInactive(ctx);
    }
     @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 接收到消息时的处理逻辑
        System.out.println("Received message: " + msg.text());
         ctx.channel().writeAndFlush(new TextWebSocketFrame("服务端收到你发来消息了"));
    }
     public static void sendMessage(String channelId, String message) {
        // 向指定连接发送消息
        ChannelHandlerContext ctx = channelMap.get(channelId);
        if (ctx != null) {
            ctx.channel().writeAndFlush(new TextWebSocketFrame(message));
        }
    }

    public static void sendToAll(String msg){
        for (ChannelHandlerContext ctx : channelMap.values()) {
            if(ctx.channel().isOpen() && ctx.channel().isActive()){
                ctx.channel().writeAndFlush(new TextWebSocketFrame(msg));
            }
        }
    }
}